<?php
/**
 * User: wangxiaoxiao
 * Date: 2020年6月28日  0028
 * Time: 下午 18:05
 * Description:
 */

namespace api\lib;

use api\models\Order;
use api\models\Good;
use common\config\AppConf;
use common\helpers\StringHelper;
use yii\db\Expression;

class OrderHelper extends BaseHelper
{

    /**
     * User: wangxiaoxiao
     * Description: 生成唯一订单号
     * @return string
     */
    public static function orderSn()
    {
        return md5(uniqid(mt_rand(), true));
    }

    /**
     * User: wangxiaoxiao
     * Description: 生成秒杀订单
     * @param int $userId
     * @param int $goodsId
     * @return array
     */
    public static function addOrder($userId = 1, $goodsId = 1)
    {
        //查询商品
        $goodsData = Good::findOne($goodsId);

        //查询库存是否售空
        if ($goodsData->stock <= 0) {
            return self::renderError('商品库存已售空', AppConf::APP_NO_DB);
        }

        //组装数据
        $orderModel = new Order();
        $orderModel->order_id = self::orderSn();
        $orderModel->user_id = $userId;
        $orderModel->goods_id = $goodsId;

        if (!$orderModel->save()) {
            return self::renderError(StringHelper::getErrorSummary($orderModel->getErrors()), AppConf::APP_NO_DB);
        }

        //减库存
        $re = Good::updateAll(['stock' => new Expression('stock - 1')], ['and', ['id' => $goodsId], ['>', 'stock', '0']]);
        if ($re <= 0) {
            return self::renderError('商品库存已售空');
        }
        return self::renderSuccess();
    }

}